import { login } from '@/store/actions/login';
import { Card,Form, Input, Button, Checkbox ,message } from 'antd'
import { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';
import logo from '../../assets/logo.png'
import './index.scss'

const Login = () => {
  const dispatch = useDispatch()
  const history  = useHistory()
  const location = useLocation()

  const [loading,setLoading] =  useState(false)
  const onFinish = async (values) => {
    setLoading(true)
    try {
      await dispatch(login(values))
      message.success('登陆成功', 1, () => {
        const from = location.state?.from?location.state.from:'/home'
        history.replace(from)
      })
    } catch (error) {
      setLoading(false)
      message.error(error.response.data.message, 1)
    }
  };

  // const onFinishFailed = (errorInfo) => {
  //   console.log('Failed:', errorInfo);
  // };
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form 
          autoComplete="off" 
          initialValues=
            {{
            mobile: '13911111111',
            code: '246810',
            agree: true
            }}  
        onFinish={onFinish} 
        validateTrigger={['onBlur', 'onChange']}>
          <Form.Item name="mobile"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur'
              },
              { required: true, message: '请输入手机号' }
            ]} >
            <Input placeholder="请输入手机号"/>
          </Form.Item>

          <Form.Item  name="code"
            rules={[
              { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
              { required: true, message: '请输入验证码' }
            ]}
          >
            <Input placeholder="请输入验证码" maxLength={6}/>
          </Form.Item>

          <Form.Item 
            name="agree"
            valuePropName="checked"
            rules={[
            {
              validator: (_, value) =>
                value ? Promise.resolve() : Promise.reject(new Error('请同意先关协议！！')),
            },
          ]}
        >
            <Checkbox>请同意相关的隐私协议</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button block type="primary" htmlType="submit"  loading={loading}>
              登陆
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login